package main.java.LeetCode.ClassicalAlgorithm.RateLimit.Impl;

import main.java.LeetCode.ClassicalAlgorithm.RateLimit.RateLimit;

public class LeakyBucket implements RateLimit {

    private final long capacity;
    private long water;
    private long beginTime;
    private final long duration;


    public LeakyBucket(int granularity,long capacity){
        this.capacity = capacity;
        water = 0;
        beginTime = System.currentTimeMillis();
        duration = 1000/granularity;
    }
    @Override
    public synchronized boolean isLimit(long count) {
        long now = System.currentTimeMillis();
        water = Math.max(0,water - (now-beginTime)/duration);
        beginTime = now;

        if(count>=capacity-water)
            return true;
        water = water+count;
        return false;
    }
}
